package com.kanshu.ksgb.fastread.doudou.module.book.activity;

import android.graphics.Color;
import android.os.Bundle;
import android.support.v7.widget.RecyclerView;
import android.text.TextUtils;
import android.util.TypedValue;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.animation.Animation;
import android.view.animation.AnimationUtils;
import android.widget.Button;
import android.widget.FrameLayout;
import android.widget.TextView;

import com.alibaba.android.arouter.facade.annotation.Route;
import com.dl7.recycler.helper.RecyclerViewHelper;
import com.dl7.recycler.listener.OnRecyclerViewItemClickListener;
import com.dl7.recycler.listener.OnRecyclerViewItemLongClickListener;
import com.kanshu.ksgb.fastread.doudou.R;
import com.kanshu.ksgb.fastread.doudou.app.constants.ARouterConfig;
import com.kanshu.ksgb.fastread.doudou.app.constants.Constants;
import com.kanshu.ksgb.fastread.doudou.common.business.utils.ReaderJumpConfig;
import com.kanshu.ksgb.fastread.doudou.base.baseui.BaseActivity;
import com.kanshu.ksgb.fastread.doudou.common.net.bean.BaseResult;
import com.kanshu.ksgb.fastread.doudou.common.util.DisplayUtils;
import com.kanshu.ksgb.fastread.doudou.common.util.SwipeRefreshHelper;
import com.kanshu.ksgb.fastread.doudou.common.util.ToastUtil;
import com.kanshu.ksgb.fastread.doudou.common.util.Utils;
import com.kanshu.ksgb.fastread.doudou.common.view.EmptyLayout;
import com.kanshu.ksgb.fastread.doudou.common.view.LoadingDialog;
import com.kanshu.ksgb.fastread.doudou.common.view.TitlebarView;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookRecentAdapter;
import com.kanshu.ksgb.fastread.doudou.module.book.adapter.BookShelfAdapter;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.BookInfo;
import com.kanshu.ksgb.fastread.doudou.common.business.commonbean.ReaderInputParams;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.RecentBookInfo;
import com.kanshu.ksgb.fastread.doudou.module.book.bean.ShelfTopData;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ReaderFinishEvent;
import com.kanshu.ksgb.fastread.doudou.common.business.event.ShelfEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DeleteDownLoadEvent;
import com.kanshu.ksgb.fastread.doudou.module.download.event.DownloadProgressEvent;
import com.kanshu.ksgb.fastread.doudou.module.reader.utils.SettingManager;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.ShelfPresenter;
import com.kanshu.ksgb.fastread.doudou.module.book.presenter.ShelfView;
import com.kanshu.ksgb.fastread.doudou.module.book.retrofit.requestparams.ShelfRequestParams;
import com.kanshu.ksgb.fastread.doudou.module.book.fragment.AdBookShelfFragment;
import com.lcodecore.tkrefreshlayout.TwinklingRefreshLayout;
import com.umeng.analytics.MobclickAgent;

import org.greenrobot.eventbus.EventBus;
import org.greenrobot.eventbus.Subscribe;
import org.greenrobot.eventbus.ThreadMode;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 最近阅读
 */
@Route(path = ARouterConfig.RECENT_READ_LIST)
public class RecentReadActivity extends BaseActivity implements OnRecyclerViewItemClickListener, OnRecyclerViewItemLongClickListener, ShelfView {
    @BindView(R.id.recyler_view)
    RecyclerView mRecylerView;
    @BindView(R.id.empty_layout)
    EmptyLayout mEmptyLayout;
    @BindView(R.id.swipe_refresh)
    TwinklingRefreshLayout mSwipeRefresh;
    @BindView(R.id.shelf_del_btn)
    Button mShelfDelBtn;
    List<RecentBookInfo> mBookInfos = new ArrayList<>();
    BookRecentAdapter mAdapter;
    ShelfPresenter mShelfPresenter = new ShelfPresenter(lifeCyclerSubject);
    ShelfRequestParams mParams = new ShelfRequestParams();
    int mCheckCount;
    TextView mSelectAllTv;
    LoadingDialog mLoadingDialog;
    @BindView(R.id.title_layout)
    TitlebarView mTitleLayout;

    @BindView(R.id.title_place_holder)
    View mFTitlePlaceHolder;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.fragment_shelf_layout);
        ButterKnife.bind(this);
        mTitleLayout.setVisibility(View.GONE);
        init();

    }

    @OnClick(R.id.shelf_del_btn)
    public void processDelBooks() {
        if (mCheckCount == 0) {
            ToastUtil.showMessage(this, "请选择要删除的书本");
            return;
        }
        mLoadingDialog = new LoadingDialog(this, "加载中");
        mLoadingDialog.show();
        String book_ids = "";
        for (int i = mBookInfos.size() - 1; i >= 0; i--) {
            RecentBookInfo bookInfo = mBookInfos.get(i);
            if (bookInfo.is_selected) {
                book_ids += (bookInfo.book_id + ",");
            }
        }
        if (TextUtils.isEmpty(book_ids)) {
            return;
        }
        // 批量删除
        book_ids = book_ids.substring(0, book_ids.length() - 1);
        mShelfPresenter.deleteRecentBook(book_ids);
    }

    private void init() {
        //goneTitlebar(true);
        setTitle("最近阅读");
        mShelfPresenter.attachView(this);
        mAdapter = new BookRecentAdapter(this, mBookInfos);
        mAdapter.setOnItemLongClickListener(this);
        mAdapter.setOnItemClickListener(this);
        mAdapter.setRequestDataListener(() -> {
            if (mAdapter.isEditable()) {
                return;
            }
            if (mParams.page == 1) {
                mParams.page++;
            }
            mShelfPresenter.getRecentInfos(mParams);
        });
        mEmptyLayout.setRetryListener(() -> {
            mParams.page = 1;
            showLoading(null);
            mShelfPresenter.getRecentInfos(mParams);
        });
        // handleSwipeConflict(mSwipeRefresh, mRecylerView, mAdapter);
        mParams.page = 1;
        mParams.num = 20;
        SwipeRefreshHelper.init(mSwipeRefresh, () -> {
            mParams.page = 1;
            mShelfPresenter.getRecentInfos(mParams);
        });
        RecyclerViewHelper.initRecyclerViewG(this, mRecylerView, false, mAdapter, AdBookShelfFragment.MAX_COLUMN);
        showLoading(null);
        mShelfPresenter.getRecentInfos(mParams);
        EventBus.getDefault().register(this);

    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        mShelfPresenter.detachView();
        EventBus.getDefault().unregister(this);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleShelfEvent(ShelfEvent event) {
        if (event.code == ShelfEvent.DELETE_RECENT_BOOK) {
            mLoadingDialog.dismiss();
            processCancelAll();
            cancelEditMode();
        }
    }
    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleFinishEvent(ReaderFinishEvent event) {
        mParams.page = 1;
        mShelfPresenter.getRecentInfos(mParams);
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDeleteDownLoadEvent(DeleteDownLoadEvent event) {
        mAdapter.notifyDataSetChanged();
    }

    @Subscribe(threadMode = ThreadMode.MAIN)
    public void handleDownloadProgressEvent(DownloadProgressEvent event) {
        if(event.isGroupFinish) {
            mAdapter.notifyDataSetChanged();
        }
    }

    @Override
    public void onItemClick(View view, int position) {
        position = position - mAdapter.getHeaderViewsCount();
        // 编辑模式
        if (mAdapter.isEditable() && !BookShelfAdapter.isInvalidBook(mBookInfos.get(position).book_id)) {
            RecentBookInfo item = mBookInfos.get(position);
            item.is_selected = !item.is_selected;
            processCheck(item.is_selected);
            mAdapter.notifyDataSetChanged();
            return;
        }
        if (position < mBookInfos.size()) {
            RecentBookInfo info = mBookInfos.get(position);
            int order = TextUtils.isEmpty(info.c_order) ? 1 : Integer.parseInt(info.c_order);
            if (SettingManager.getInstance().isReadBook(info.book_id)) {
                ReaderInputParams params = new ReaderInputParams();
                params.book_id = info.book_id;
                ReaderJumpConfig.startReaderActivity(this, params);
                return;
            }
            ReaderInputParams params = new ReaderInputParams();
            params.book_id = info.book_id;
            params.content_id = info.content_id;
            params.order = order + "";
            params.book_title = info.book_title;
            ReaderJumpConfig.startReaderActivity(this, params);
        }
    }

    @Override
    public boolean onItemLongClick(View view, int position) {
        if (mAdapter.isEditable()) {
            return true;
        }
        mSwipeRefresh.finishRefreshing();
        position = position - mAdapter.getHeaderViewsCount();
        if (position < mBookInfos.size()) {
            showEditMode();
            mAdapter.setEditable(true);
            Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_up_in);
            mShelfDelBtn.startAnimation(animation);
            DisplayUtils.visible(mShelfDelBtn);
            showDelInfo();
            mSwipeRefresh.setEnableRefresh(false);
            mAdapter.enableLoadMore(false);
            return true;
        }
        return false;
    }


    @Override
    public void showShelfBookInfos(List<BookInfo> list, boolean isFromNet) {
    }

    @Override
    public void showAddToShelf(BookInfo info) {
    }

    @Override
    public void showNewRecentBookInfos(BaseResult<List<RecentBookInfo>> info) {
        if (mParams.page == 1) {
            if (Utils.isEmptyList(info.result.data)) {
                //mEmptyLayout.setEmptyMessage("暂无记录");
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
                SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
                mBookInfos.clear();
                mAdapter.notifyDataSetChanged();
                return;
            }
            mBookInfos.clear();
            mAdapter.setIsNoMoreData(false);
        }
//        mBookInfos.addAll(info.result.data);
        addAll(info.result.data);
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
        SwipeRefreshHelper.swipeRefreshCompleted(mSwipeRefresh, mAdapter);
        if (mParams.page >= info.result.total_page) {
            mAdapter.noMoreData();
        } else {
            mParams.page++;
        }
        mAdapter.notifyDataSetChanged();
    }

    private void addAll(List<RecentBookInfo> list) {
        if (Utils.isEmptyList(list)) {
            return;
        }
        for (RecentBookInfo info : list) {
            boolean flg = false;
            for (RecentBookInfo bookInfo : mBookInfos) {
                if (TextUtils.equals(bookInfo.book_id, info.book_id)) {
                    flg = true;
                    break;
                }
            }
            if (!flg) {
                mBookInfos.add(info);
            }
        }
    }


    @Override
    public void showRecentBookInfos(BaseResult<ShelfTopData> info) {
    }

    @Override
    public void showContent(ShelfTopData shelfTopData) {

    }

    @Override
    public void showError(int errCode, String errDesc) {
        if (Utils.isEmptyList(mBookInfos)) {
            if (errCode == Constants.ErrCode.NoData) {
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_DATA);
            } else {
                mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_NO_NET);
            }
        }
    }

    @Override
    public void showLoading(String s) {
        mEmptyLayout.setEmptyStatus(EmptyLayout.STATUS_LOADING);
    }

    @Override
    public void dismissLoading() {
        if (mEmptyLayout != null) {
            mEmptyLayout.hide();
        }
    }

    private TextView addEditModeBtn(FrameLayout container, CharSequence s) {
        TextView tv = new TextView(this);
        tv.setText(s);
        tv.setGravity(Gravity.CENTER);
        tv.setTextColor(Color.parseColor("#333333"));
        tv.setTextSize(TypedValue.COMPLEX_UNIT_PX, getResources().getDimensionPixelSize(R.dimen.px_46));
        Utils.setBackground(tv, getResources().getDrawable(R.drawable.edit_mode_bg));
        int width = getResources().getDimensionPixelSize(R.dimen.px_132);
        int height = getResources().getDimensionPixelSize(R.dimen.px_75);
        FrameLayout.LayoutParams params = new FrameLayout.LayoutParams(width, height);
        params.gravity = Gravity.CENTER_VERTICAL;
        container.addView(tv, params);
        return tv;
    }

    private void cancelEditMode() {
        mTitle.getBack().setVisibility(View.VISIBLE);
        mSelectAllTv.setVisibility(View.GONE);
        mTitle.getRightContainer().removeAllViews();
        mAdapter.setEditable(false);
    }

    private void showEditMode() {
        mTitle.getBack().setVisibility(View.GONE);
        mAdapter.setEditable(true);
        mSelectAllTv = addEditModeBtn(mTitle.getLeftContainer(), "全选");
        mSelectAllTv.setOnClickListener(v -> processSelectAll());
        addEditModeBtn(mTitle.getRightContainer(), "取消").setOnClickListener(v -> {
            cancelEditMode();
            processCancelAll();
        });
    }

    private void processSelectAll() {
        int count = 0;
        for (RecentBookInfo bookInfo : mBookInfos) {
            bookInfo.is_selected = true;
            count++;
        }
        mCheckCount = count;
        showDelInfo();
        mAdapter.setEditable(true);
        mAdapter.notifyDataSetChanged();
    }

    private void processCancelAll() {
        mCheckCount = 0;
        showDelInfo();
        mAdapter.setEditable(false);
        // 重新获取数据
        mParams.page = 1;
        mShelfPresenter.getRecentInfos(mParams);
        Animation animation = AnimationUtils.loadAnimation(this, R.anim.push_up_out);
        mShelfDelBtn.startAnimation(animation);
        DisplayUtils.gone(mShelfDelBtn);
        mSwipeRefresh.setEnableRefresh(true);
        mAdapter.enableLoadMore(true);
    }

    /**
     * 显示删除按钮上的信息
     */
    private void showDelInfo() {
        mShelfDelBtn.setText(getString(R.string.del_format, String.valueOf(mCheckCount)));
    }

    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            if (mAdapter.isEditable()) {
                cancelEditMode();
                processCancelAll();
                return true;
            }
        }
        return super.onKeyDown(keyCode, event);
    }

    /**
     * 处理删除选中
     */
    private void processCheck(boolean checked) {
        if (checked) {
            mCheckCount++;
        } else {
            mCheckCount--;
        }
        showDelInfo();
    }

    @Override
    protected void onResume() {
        super.onResume();
        MobclickAgent.onPageStart(getClass().getSimpleName());
    }

    @Override
    protected void onPause() {
        super.onPause();
        MobclickAgent.onPageEnd(getClass().getSimpleName());
    }
}